package com.raidroid.rdwhois;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.admob.android.ads.AdManager;
import com.admob.android.ads.AdView;

public class RDWhois extends Activity {
	SQLiteDatabase db = null;
	private ServerItem si = null;
	final Activity self = this;
	
	static final String[] goDaddyExtensions = new String[]{".com", ".info", ".net", ".org", ".me", 
			".mobi", ".us", ".biz", ".mx", ".ca", ".it", ".ws", ".ag", ".com.ag", ".net.ag", 
			".org.ag", ".am", ".asia", ".at", ".be", ".bz", ".com.bz", ".net.bz", ".cc", 
			".cn", ".com.cn", ".net.cn", ".org.cn", ".de", ".es", ".com.es", ".nom.es", 
			".org.es", ".eu", ".fm", ".gs", ".in", ".co.in", ".firm.in", ".gen.in", 
			".ind.in", ".net.in", ".org.in", ".jobs", ".jp", ".ms", ".com.mx", ".nl", 
			".nu", ".co.nz", ".net.nz", ".org.nz", ".tc", ".tk", ".tv", ".tw", ".com.tw", 
			".org.tw", ".idv.tw", ".co.uk", ".me.uk", ".org.uk", ".vg"};
		
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);         
        setContentView(R.layout.main);      
        
        //Start ad        
        if(findViewById(R.id.ad)!= null){
	        AdView adView = (AdView)findViewById(R.id.ad);    
		        AdManager.setTestDevices( new String[] {
		        		AdManager.TEST_EMULATOR, // Android emulator
		        		"E83D20734F72FB3108F104ABC0FFC738", // My T-Mobile G1 Test Phone
		        		} );
		        adView.requestFreshAd();        
        }
        //End ad
        
        //requestWindowFeature(Window.FEATURE_NO_TITLE);        
        Button Button01 = (Button) findViewById(R.id.Button01);
        Button01.setOnClickListener(mWhoisClickListener);    
        Spinner serversCombo = (Spinner) findViewById(R.id.Spinner01);
        serversCombo.setOnItemSelectedListener(mServersComboListener);
        PopulateSpinner(serversCombo);
        PopulateAutoComplateTextView();
    }
	
	@Override
	public void onResume(){
		super.onResume();
		Spinner serversCombo = (Spinner) findViewById(R.id.Spinner01);
        PopulateSpinner(serversCombo);
        PopulateAutoComplateTextView();
	}
 
  
    public void InsertSearchedWord(String word){
    	DBAdapter db = new DBAdapter(this);
    	db.open();
    	db.insertWord(word);
    	db.close();
    }
    
    public void DisplayNotice(String notice)
    {
        Toast.makeText(this,
                notice,
                Toast.LENGTH_LONG).show();
    }
    
    private OnItemSelectedListener mServersComboListener = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {			
			si = (ServerItem) arg0.getSelectedItem();
			TextView label4 = (TextView) findViewById(R.id.TextView04);
			label4.setText(si.get_description());
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub			
		}
    	
	};
	
	private void PopulateAutoComplateTextView(){
		AutoCompleteTextView QueryText = 
    		(AutoCompleteTextView) findViewById(R.id.TxtQuery);
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.ac_list_item);
		DBAdapter db = new DBAdapter(this);
    	db.open();    	
    	Cursor c = db.getAllWords();
    	if (c.moveToFirst())
        {
            do {      
            	adapter.add(c.getString(1));
            } while (c.moveToNext());
        }        
        db.close();		
        QueryText.setAdapter(adapter);
	}
    
    private void PopulateSpinner(Spinner combo)
    {
    	ArrayAdapter<ServerItem> m_adapterForSpinner;
        m_adapterForSpinner = new ArrayAdapter<ServerItem>(this, android.R.layout.simple_spinner_item);
        m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	
    	DBAdapter db = new DBAdapter(this);
    	db.open();    	
    	Cursor c = db.getAllServers();
    	if (c.moveToFirst())
        {
            do {          
            	m_adapterForSpinner.add(new ServerItem(c.getInt(0), 
            			c.getString(1), c.getString(2), c.getString(3), c.getString(4)));
            } while (c.moveToNext());
        }        
        db.close();
        combo.setAdapter(m_adapterForSpinner);
    }
    
    private void DisplayRequest(String str, String query){   	
    	final Dialog dialog = new Dialog(this);   	
        dialog.setContentView(R.layout.resultdialog);
        dialog.setTitle(R.string.Query_Result);
        
        TextView qr = (TextView) dialog.findViewById(R.id.QueryResult);
        qr.setText(str);
        Button DialogClose = (Button) dialog.findViewById(R.id.btnClose);
        DialogClose.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				PopulateAutoComplateTextView();
				dialog.dismiss();
			}
		});
        Button DialogButtonGoDaddy = (Button) dialog.findViewById(R.id.DialogButtonGoDaddy);
        DialogButtonGoDaddy.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				OpenUrlOnBrowser("http://affiliate.godaddy.com/redirect/1A64E86AFD7D7868E40C00297845C79C");
			}
		});        
        if(!IsValidExtensionForGodaddy(query)){
        	DialogButtonGoDaddy.setVisibility(View.GONE);
        }        
        dialog.show();        
    }
    
    private boolean IsValidExtensionForGodaddy(String url){
    	boolean result = false;
    	for(int i = 0;i < goDaddyExtensions.length; i++){
    		if(url.contains(goDaddyExtensions[i].toString())){
    			result = true;
    			break;
    		}
    	}    	
    	return result;
    }

    //Start Whois Part
    String QueryResult = "";
    String Query = "";
    final Handler wHandler = new Handler();
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
        	if(!QueryResult.equals(""))
    		{        			
    			DisplayRequest(QueryResult, Query);
    		}
        }
    };
    
    String ErrorMessage = "";
    final Handler eHandler = new Handler();
    final Runnable ShowError = new Runnable() {
        public void run() {
        	ShowAlert(getString(R.string.Alert), ErrorMessage);
        }
    };

    private OnClickListener mWhoisClickListener = new OnClickListener() {
        public void onClick(View v) {    	 
        	AutoCompleteTextView QueryText = 
        		(AutoCompleteTextView) findViewById(R.id.TxtQuery);
        	Query = QueryText.getText().toString().trim();
        	InsertSearchedWord(Query);        	
        	if(!Query.equals(""))
        	{            		
        		final ProgressDialog pd = 
        			ProgressDialog.show(RDWhois.this, 
        					getString(R.string.Retrieving_Results), 
        					getString(R.string.Please_Wait_Message));
        		
        		Thread t = new Thread() {
                    public void run() {
                    	QueryResult = whois(si, Query);
                    	pd.dismiss();
                    	wHandler.post(mUpdateResults);
                    }
                    
                    public String whois(ServerItem si, String Query)
                    {
                    	return whois(si.get_server(), Integer.parseInt(si.get_port()), Query);
                    }                    
                    public String whois(String Host, int Port, String Query) {
                    	String strReturn = "";
                    	try {    		
                    		
                    		Socket s = new Socket(Host, Port);
                			InputStreamReader isr = new InputStreamReader(s.getInputStream());
                			BufferedReader br = new BufferedReader(isr);
                			PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
                			pw.println(Query + "\r");
                			StringBuffer sb = new StringBuffer();
                			
                			while ((strReturn = br.readLine()) != null) {
                				System.out.println(strReturn);
                				sb.append(strReturn);
                				sb.append("\n");
                			}
                			strReturn = sb.toString();                					
                		} catch (UnknownHostException e) {
                			ErrorMessage = getString(R.string.connection_error_string);
                			eHandler.post(ShowError);
                		} catch (IOException e) {
                			ErrorMessage = getString(R.string.connection_error_string);
                			eHandler.post(ShowError);
                		}
                		return strReturn;
                    }                    
                };
                t.start();
        	}        	
        	else
        	{
        		DisplayNotice(getString(R.string.Domain_Name_is_not_valid));
        	}
        }
    };
    
    //End Whois Part
   
    private void ShowAlert(String Title, String Alert)
    {
    	Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(Title);
        builder.setMessage(Alert);
        builder.setPositiveButton("Ok", null);
        builder.show(); 
    }
    
    private void OpenUrlOnBrowser(String url){
    	final String redirectionUrl = url;
    	new  AlertDialog.Builder(RDWhois.this)
		.setMessage(R.string.RedirectionAlertDialogMessage)
		.setPositiveButton(R.string.Ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent i = new Intent();
		        ComponentName comp = 
		        	new ComponentName("com.android.browser", 
		        			"com.android.browser.BrowserActivity");
		        i.setComponent(comp);
		        i.setAction("android.intent.action.VIEW");
		        i.addCategory("android.intent.category.BROWSABLE");
		        Uri uri = Uri.parse(redirectionUrl);
		        i.setData(uri);
		        self.startActivity(i);
				dialog.dismiss();
			}
		}).setNeutralButton(R.string.Cancel, new DialogInterface.OnClickListener() {			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();						
			}
		})
		.setTitle(R.string.Confirm)
		.show();        
    }
    
   
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
		if(item.hasSubMenu() == false){		
			if(item.getOrder() == 0)
			{	
				Intent i = new Intent(RDWhois.this, SettingsList.class);
		        startActivity(i);
			}
		}
    	return true;
    }
    
}